package cn.itcast.xuesheng.web.servlet;

import cn.itcast.xuesheng.domain.User;
import cn.itcast.xuesheng.service.impl.UserServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/CheckUserServlet")
public class CheckUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String username = request.getParameter("username");
        Map<String,Object> map=new HashMap<>();
        UserServiceImpl userService=new UserServiceImpl();
        User checkuser = userService.check(username);
        if (checkuser==null){
            map.put("checkUser",true);
            map.put("msg","用户名可用");
        }
        else {
            map.put("checkUser",false);
            map.put("msg","用户名太受欢迎了,请换一个");
        }
        ObjectMapper objectMapper=new ObjectMapper();
        objectMapper.writeValue(response.getWriter(),map);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
